﻿using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace InfiniTec.IO
{
	class MemoryMappedFileSafeHandle: SafeHandle
	{
		private static long _PageFileUsage;

		internal static long PageFileUsage
		{
			get { return _PageFileUsage; }
		}

		private long _SizeInPageFile;
		public long SizeInPageFile
		{
			get { return _SizeInPageFile; }
			set
			{
				Interlocked.Add(ref _PageFileUsage, -SizeInPageFile);
				_SizeInPageFile = value;
				Interlocked.Add(ref _PageFileUsage, SizeInPageFile);
			}
		}

		public MemoryMappedFileSafeHandle() : base(IntPtr.Zero, true)
		{
		}

		protected override bool ReleaseHandle()
		{
			Interlocked.Add(ref _PageFileUsage, -SizeInPageFile);
			return SafeNativeMethods.CloseHandle(handle);
		}

		public override bool IsInvalid
		{
			get { return handle == IntPtr.Zero; }
		}
	}
}
